package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 开始时间戳
     * 2022-1-1 0:0:0的秒数
     */
    private static final long BEGIN_TIMESTAMP=1640995200L;

    /**
     * 时间戳左移的位数
     */
    private static final int COUNT_BITS=32;

    public long generateId(String keyPrefix){
        long second = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        long timestamp=second-BEGIN_TIMESTAMP;
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long increment = stringRedisTemplate.opsForValue().increment("hm-dianping:icr:" + keyPrefix + ":" + date);
        return timestamp << COUNT_BITS | increment;
    }

}
